package com.tengju.bff.interfaces.covercharge.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.idanchuang.component.base.JsonResult;
import com.tengju.bff.interfaces.covercharge.constant.ContractFromEnum;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeErrorCode;
import com.tengju.bff.interfaces.covercharge.constant.IdentityTypeEnum;
import com.tengju.bff.interfaces.covercharge.constant.SignIdentityEnum;
import com.tengju.bff.interfaces.covercharge.dto.SelfCertificationDto;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceSelfCertification;
import com.tengju.bff.interfaces.covercharge.entity.vo.LeTaxRegisteredAndReturnResult;
import com.tengju.bff.interfaces.covercharge.entity.vo.SelfCertificationQuery;
import com.tengju.bff.interfaces.covercharge.entity.vo.contract.ApplyCertificateReqVo;
import com.tengju.bff.interfaces.covercharge.entity.vo.contract.MemberAddStartReqVo;
import com.tengju.bff.interfaces.covercharge.entity.vo.contract.MemberAddStartResVo;
import com.tengju.bff.interfaces.covercharge.handler.CoverChargeException;
import com.tengju.bff.interfaces.covercharge.service.*;
import com.tengju.bff.interfaces.covercharge.util.UserUtils;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.bff.interfaces.shared.servlet.ManageEntrance;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/manage/backstage/contract")
@Api(value = "contract", tags = "后台合同相关")
@ManageEntrance
public class AdminContractController {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IServiceContractService contractService;
    @Autowired
    private IServiceLetaxRegisteredService serviceLetaxRegisteredService;
    @Autowired
    private SelfCertificationService selfCertificationService;
    @Resource
    private IServiceSelfCertificationService serviceSelfCertificationService;

    @ResponseBody
    @PostMapping("/dealMemberAddStart")
    @ApiOperation(value = "签署合同成功会员入星", notes = "签署合同成功会员入星")
    public ApiResponse<MemberAddStartResVo> signContract(@RequestBody MemberAddStartReqVo reqVo) {
        log.info("手动触发-签署合同成功会员入星");
        MemberAddStartResVo resVo = new MemberAddStartResVo();
        String contractIds = reqVo.getContractId();
        if (StringUtils.isBlank(contractIds)) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "合同Id不能为空");
        }
        String[] contractArray = contractIds.split(",");
        StringBuilder sucContractId = new StringBuilder();
        StringBuilder failContractId = new StringBuilder();
        for (String contractId : contractArray) {
            String bizId = String.valueOf(IdWorker.getId());
            boolean result = memberService.dealMemberAddStart(bizId, contractId);
            if (result) {
                sucContractId.append(contractId).append(",");
            } else {
                failContractId.append(contractId).append(",");
            }
        }
        String suc = sucContractId.toString();
        String fail = failContractId.toString();
        resVo.setSucContractId(StringUtils.isBlank(suc) ? null : suc.substring(0, suc.length() - 1));
        resVo.setFailContractId(StringUtils.isBlank(fail) ? null : fail.substring(0, fail.length() - 1));
        return ApiResponse.newSuccess(resVo);
    }


    @ResponseBody
    @PostMapping("/applyCert")
    @ApiOperation(value = "证书申请", notes = "证书申请")
    public ApiResponse<String> applyCert(HttpServletRequest request, @RequestBody ApplyCertificateReqVo reqVo) {
        //平台标识
        String platformCode = UserUtils.getPlatformCode(request);
        //获取用户Id
        Integer idCode = UserUtils.getIdCode(request);
        contractService.applyCertificate(platformCode, idCode, reqVo.getType(), reqVo);
        return ApiResponse.newSuccess("证书申请提交成功");
    }

    @ResponseBody
    @PostMapping("/leTaxApplyCert")
    @ApiOperation(value = "乐税和自认证证书申请", notes = "乐税和自认证证书申请")
    public ApiResponse<String> leTaxApplyCert(HttpServletRequest request, @RequestBody SelfCertificationDto selfCertificationDto) {
        Assert.notNull(selfCertificationDto.getIdCode(), "代理IdCode不能为空");
        Assert.notNull(selfCertificationDto.getPlatformCode(), "平台不能为空");
        Assert.notNull(selfCertificationDto.getCurrentIdentity(), "当前身份不能为空");

        if (selfCertificationDto.getCurrentIdentity().equals(SignIdentityEnum.person.getCode()) || selfCertificationDto.getCurrentIdentity().equals(SignIdentityEnum.no_identity.getCode())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.BUSINESS_ERROR.getCode(), "身份不是乐税注册个体户和自认证");
        }

        SelfCertificationQuery selfCertificationQuery = new SelfCertificationQuery();
        if (selfCertificationDto.getCurrentIdentity().equals(SignIdentityEnum.regist_soho.getCode())) {//乐税
            //获取乐税返回信息
            LeTaxRegisteredAndReturnResult leTaxInfo = serviceLetaxRegisteredService.leTaxRegisteredAndReturnInfo(selfCertificationDto.getIdCode(), selfCertificationDto.getPlatformCode());
            log.info("乐税申请证书请求参数:{}", leTaxInfo);
            if (Objects.isNull(leTaxInfo)) {
                return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), "没有乐税注册信息");
            }
            selfCertificationQuery.setIdcardName(leTaxInfo.getIdcardName());
            selfCertificationQuery.setIdcardNo(leTaxInfo.getIdcardNo());
            selfCertificationQuery.setIdcardType(IdentityTypeEnum.TYPE_0.getType());
            selfCertificationQuery.setCompanyNo(leTaxInfo.getMerchantTaxNumber());
            selfCertificationQuery.setCompanyName(leTaxInfo.getMerchantName());
            selfCertificationQuery.setLegalMobile(leTaxInfo.getPhoneNumber());
            selfCertificationQuery.setType(ContractFromEnum.LE_TAX_INDIVIDUAL.getFrom());
            selfCertificationQuery.setIdCode(selfCertificationDto.getIdCode());
            selfCertificationQuery.setPlatformCode(selfCertificationDto.getPlatformCode());

        } else {
            //获取自认证记录
            QueryWrapper serviceSelfCertificationInfoQueryWrapper = new QueryWrapper();
            serviceSelfCertificationInfoQueryWrapper.eq("platform_code", selfCertificationDto.getPlatformCode());
            serviceSelfCertificationInfoQueryWrapper.eq("id_code", selfCertificationDto.getIdCode());
            serviceSelfCertificationInfoQueryWrapper.eq("status", 1);
            ServiceSelfCertification selfCertificationInfo = serviceSelfCertificationService
                    .getOne(serviceSelfCertificationInfoQueryWrapper);
            if (Objects.isNull(selfCertificationInfo)) {
                return ApiResponse.newFailure(CoverChargeErrorCode.BUSINESS_ERROR.getCode(), "身份没有认证成功，无法申请!");
            }
            selfCertificationQuery.setIdCode(selfCertificationInfo.getIdCode());
            selfCertificationQuery.setType(selfCertificationInfo.getType());
            selfCertificationQuery.setPlatformCode(selfCertificationInfo.getPlatformCode());
            selfCertificationQuery.setIdcardType(selfCertificationInfo.getIdcardType());
            selfCertificationQuery.setIdcardNo(selfCertificationInfo.getIdcardNo());
            selfCertificationQuery.setIdcardName(selfCertificationInfo.getIdcardName());
            selfCertificationQuery.setCompanyNo(selfCertificationInfo.getCompanyNo());
            selfCertificationQuery.setCompanyName(selfCertificationInfo.getCompanyName());
            selfCertificationQuery.setLegalMobile(selfCertificationInfo.getLegalMobile());
        }

        try {
            log.info("后台重新申请证书请求参数:{}", selfCertificationQuery);
            selfCertificationService.registeredApplyCert(selfCertificationQuery);
            return ApiResponse.newSuccess("证书申请提交成功");
        } catch (CoverChargeException ce) {
            log.error("后台重新申请证书报错", ce);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), ce.getMsg());
        } catch (Exception e) {
            log.error("后台重新生成电子证书报错", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }
}
